import type { AreaVO } from '#/api/system/area/model';

import { defineStore } from 'pinia';

import { areaList } from '#/api/system/area';

interface AreaState {
  areaData: AreaVO[];
  lastUpdateTime: number;
  isLoading: boolean;
}

export const useAreaStore = defineStore('area', {
  state: (): AreaState => ({
    areaData: [],
    lastUpdateTime: 0,
    isLoading: false,
  }),
  getters: {
    // 判断缓存是否过期（24小时）
    isCacheExpired(): boolean {
      return Date.now() - this.lastUpdateTime > 24 * 60 * 60 * 1000;
    },
    // 获取国家列表
    countries(): AreaVO[] {
      // 将 contries 重命名为 countries
      return this.areaData.filter((item) => item.type === '1');
    },
    // 获取省份列表
    provinces(): AreaVO[] {
      return this.areaData.filter((item) => item.type === '2');
    },
    // 获取城市列表（可根据省份ID筛选）
    cities(): (provinceId?: number | string) => AreaVO[] {
      return (provinceId?: number | string) => {
        const cities = this.areaData.filter((item) => item.type === '3');
        return provinceId
          ? cities.filter((city) => city.parentid === provinceId)
          : cities;
      };
    },
    // 获取区县列表（可根据城市ID筛选）
    districts(): (cityId?: number | string) => AreaVO[] {
      return (cityId?: number | string) => {
        const districts = this.areaData.filter((item) => item.type === '4');
        return cityId
          ? districts.filter((district) => district.parentid === cityId)
          : districts;
      };
    },
  },
  actions: {
    // 加载地区数据
    async loadAreaData(force = false) {
      // 如果数据已存在且未过期，且不强制刷新，则直接返回
      if (this.areaData.length > 0 && !this.isCacheExpired && !force) {
        return this.areaData;
      }

      // 防止重复请求
      if (this.isLoading) return this.areaData;

      this.isLoading = true;
      try {
        const res = await areaList();
        if (res && res.rows) {
          this.areaData = res.rows;
          this.lastUpdateTime = Date.now();
        }
        return this.areaData;
      } catch (error) {
        console.error('获取地区数据失败:', error);
        return [];
      } finally {
        this.isLoading = false;
      }
    },
    // 清除缓存
    clearCache() {
      this.areaData = [];
      this.lastUpdateTime = 0;
    },
  },
  // 使用 pinia-plugin-persistedstate 插件实现持久化
  persist: {
    key: 'area-store',
    storage: localStorage,
  },
});
